package com.ndood.authenticate.browser.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ndood.authenticate.core.properties.CommonConstants;
import com.ndood.authenticate.core.support.SimpleResponse;

/**
 * 添加认证失败处理类
 * http://kennylee26.iteye.com/blog/1473505
 * @author ndood
 */
//@Component("browserAuthenticationFailureHandler")
public class BrowserAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	/*@Autowired
	private SecurityProperties securityProperties;*/
	
	/**
	 * 登录失败处理
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		logger.info("登录失败");
		
		// 根据配置进行处理  TODO改成返回登录成功
		/*if(LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())){
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(CommonConstants.FAILUE,"登录失败："+exception.getMessage())));
			response.getWriter().flush();
		} else {
			super.onAuthenticationFailure(request, response, exception);
		}*/
		if(isJson(request)||isAjax(request)) {
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(CommonConstants.FAILUE,"登录失败："+exception.getMessage())));
			response.getWriter().flush();
			return;
		}
		super.onAuthenticationFailure(request, response, exception);
	}
	
	/**
	 * 判断是否是json请求
	 */
	public Boolean isJson(HttpServletRequest request) {
		boolean isJson = request.getHeader("content-type") != null
				&& request.getHeader("content-type").contains("json");
		return isJson;
	}

	/**
	 * 判断是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest httpRequest) {
		boolean isAjax = httpRequest.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString());
		return isAjax;
	}
}